<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import * as XLSX from 'xlsx'
import { GetData } from '@/api/modules/cidXiaohongshu'

// const imgDomain = 'https://img1.eprhan.cc'

const findFrom = ref({
  phone: '',
  OpenId: '',
  ClickId: '',
  LinkId: '',
  DateRange: [],
  QiWeiStatus: '',
})
const dataList: any = ref([])
const loading = ref(true)
const total = ref(0)
let excelTotal = 0
let PageSize = 20

// 获取数据
function GetDataList(PageIndex: number = 1, PageSize: number = 20) {
  const params = {
    PageIndex,
    PageSize,
    ...(findFrom.value.phone && ({ phone: findFrom.value.phone })),
    ...(findFrom.value.OpenId && ({ OpenId: findFrom.value.OpenId })),
    ...(findFrom.value.ClickId && ({ ClickId: findFrom.value.ClickId })),
    ...(findFrom.value.LinkId && ({ LinkId: findFrom.value.LinkId })),
    ...(findFrom.value.QiWeiStatus && ({ QiWeiStatus: findFrom.value.QiWeiStatus })),
    ...(findFrom.value.DateRange.length !== 0 && ({ AddTimeStart: findFrom.value.DateRange[0] })),
    ...(findFrom.value.DateRange.length !== 0 && ({ AddTimeEnd: findFrom.value.DateRange[1] })),
  }
  GetData(params).then((res: any) => {
    if (res.statusCode === 200) {
      dataList.value = res.data.items
      total.value = res.data.total
      if (total.value > excelTotal) {
        excelTotal = total.value
      }
      loading.value = false
    }
    else {
      ElMessage.error('获取数据失败')
      loading.value = false
    }
  })
}

async function ExportExcel() {
  const params = {
    PageIndex: 1,
    PageSize: excelTotal,
    ...(findFrom.value.phone && ({ phone: findFrom.value.phone })),
    ...(findFrom.value.OpenId && ({ OpenId: findFrom.value.OpenId })),
    ...(findFrom.value.ClickId && ({ ClickId: findFrom.value.ClickId })),
    ...(findFrom.value.LinkId && ({ LinkId: findFrom.value.LinkId })),
    ...(findFrom.value.QiWeiStatus && ({ QiWeiStatus: findFrom.value.QiWeiStatus })),
    ...(findFrom.value.DateRange.length !== 0 && ({ AddTimeStart: findFrom.value.DateRange[0] })),
    ...(findFrom.value.DateRange.length !== 0 && ({ AddTimeEnd: findFrom.value.DateRange[1] })),
  }
  const excelData = await GetData(params)

  // 定义中文表头映射
  const headerMapping = {
    openId: 'OpenId',
    userId: 'userId',
    nickName: '用户名',
    phone: '手机号',
    clickId: 'ClickId',
    linkId: 'LinkId',
    addTime: '记录时间',
    qiWeiStatus: '企微状态',
    orderStatus: '订单状态',
    orderNo: '订单编号',
  } as { [key: string]: string }

  // 映射数据和合并order对象
  const newData = excelData.data.items.map((item: { [key: string]: any }) => {
    if (item.order && typeof item.order === 'object') {
      Object.assign(item, item.order)
      delete item.order
    }
    const statusMap = {
      '1': '待支付',
      '3': '已支付待发货',
      '4': '已发货',
      '-4': '已发货退款',
      '-3': '未发货退款',
    }
    item.orderStatus = statusMap[item.orderStatus as keyof typeof statusMap] || ''
    item.qiWeiStatus = item.qiWeiStatus ? '已加入' : '未加入'
    return Object.keys(item).reduce((newItem, key) => {
      (newItem as { [key: string]: any })[headerMapping[key] || key] = item[key]
      return newItem
    }, {})
  })
  const wb = XLSX.utils.book_new()
  const ws = XLSX.utils.json_to_sheet(newData)
  // 设置列宽
  ws['!cols'] = [{ wch: 30 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 30 }, { wch: 20 }, { wch: 20 }, { wch: 15 }, { wch: 15 }, { wch: 30 }]
  XLSX.utils.sheet_add_aoa(ws, [Object.values(headerMapping)], { origin: 'A1' })
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
  XLSX.writeFile(wb, '小红书CID数据.xlsx')
}

// 查询
function Inquire() {
  GetDataList(1, PageSize)
}

// 翻页
function handleSizeChange(val: number) {
  GetDataList(1, val)
  PageSize = val
}

function handleCurrentChange(val: number) {
  GetDataList(val, PageSize)
}

onMounted(() => {
  GetDataList()
})
</script>

<template>
  <div>
    <PageMain>
      <SearchBar :show-toggle="false">
        <div class="header">
          <el-form label-positio="right" label-width="auto">
            <div class="from">
              <el-form-item label="手机号">
                <el-input v-model="findFrom.phone" placeholder="请输入手机号" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="OpenId">
                <el-input v-model="findFrom.OpenId" placeholder="请输入OpenId" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="ClickId">
                <el-input v-model="findFrom.ClickId" placeholder="请输入ClickId" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="LinkId">
                <el-input v-model="findFrom.LinkId" placeholder="请输入LinkId" clearable @keyup.enter="Inquire" />
              </el-form-item>
              <el-form-item label="时间">
                <el-date-picker
                  v-model="findFrom.DateRange"
                  clearable
                  type="datetimerange"
                  range-separator="到"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
              <el-form-item label="企微状态">
                <el-select v-model="findFrom.QiWeiStatus" placeholder="请选择企微状态" clearable>
                  <el-option label="已加入" :value="true" />
                  <el-option label="未加入" :value="false" />
                </el-select>
              </el-form-item>
            </div>
          </el-form>
          <div class="text-right">
            <el-button @click="Inquire">
              查询
            </el-button>
          </div>
        </div>
      </SearchBar>
      <ElDivider border-style="dashed" />
      <div class="mb-5 text-right">
        <el-button type="success" @click="ExportExcel">
          导出
        </el-button>
      </div>
      <el-table v-loading="loading" :data="dataList" stripe style="width: 100%;" border>
        <el-table-column header-align="center" width="380" prop="nickName" label="用户">
          <template #default="scope">
            <div class="userData">
              <p>用户昵称：{{ scope.row.nickName }}</p>
              <p>UserId：{{ scope.row.userId }}</p>
              <p>手机号：{{ scope.row.phone }}</p>
              <p>OpenId：{{ scope.row.openId }}</p>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" prop="linkId" label="link_id" />
        <el-table-column align="center" width="300" prop="clickId" label="click_id" />
        <el-table-column align="center" width="240" prop="addTime" label="记录时间" />
        <el-table-column align="center" width="240" prop="QiWeiStatus" label="企微状态">
          <template #default="scope">
            <el-tag :type="scope.row.qiWeiStatus ? 'success' : 'warning'">
              {{ scope.row.qiWeiStatus ? '已加入' : '未加入' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" min-width="320" prop="order" label="最近订单">
          <template #default="scope">
            <div v-if="scope.row.order">
              <p style="margin: 0;">
                订单编号：{{ scope.row.order?.orderNo }}
              </p>
              <span>
                订单状态：
              </span>
              <el-tag type="primary">
                {{ scope.row.order?.orderStatus === 1 ? '待付款'
                  : scope.row.order?.orderStatus === 3 ? '已支付待发货'
                    : scope.row.order?.orderStatus === 4 ? '已发货'
                      : scope.row.order?.orderStatus === -4 ? '发货后退款'
                        : scope.row.order?.orderStatus === -3 ? '待发货退款'
                          : scope.row.order?.orderStatus }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 10px;" />
      <el-pagination
        :default-page-size="20"
        :page-sizes="[5, 10, 20, 50, 100]"
        layout="total, sizes, ->, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </PageMain>
  </div>
</template>

<style scoped>
.header {
  display: grid;
  grid-template-columns: 6fr 1fr;

  .from {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    grid-gap: 20px;

    .el-form-item {
      margin-bottom: 0;
    }
  }
}

.userData {
  p {
    margin: 0;
  }
}
</style>
